package com.base.common.util;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 缓存系统时间，避免每次调用System.currentTimeMillis()消耗系统资源。适用于高并发、对时间精度要求不高的场景
 * 
 * @author yanjiaqiang
 * @date 2010-12-21
 * @version $Id: SystemTimer.java 7 2011-07-15 04:24:04Z JiaqiangYan@gmail.com $
 */
public class SystemTimer {
	private final static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

	private static final long tickUnit = Long.parseLong(System.getProperty("notify.systimer.tick", "50"));
	private static volatile long time = System.currentTimeMillis();

	private static class TimerTicker implements Runnable {
		@Override
		public void run() {
			time = System.currentTimeMillis();
		}
	}

	public static long currentTimeMillis() {
		return time;
	}


	static {
		executor.scheduleAtFixedRate(new TimerTicker(), tickUnit, tickUnit, TimeUnit.MILLISECONDS);
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				executor.shutdown();
			}
		});
	}
}
